package game.Enemty;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 玩家控制的角色类，代表游戏中的主要人物（如马里奥）
 * 处理角色移动、跳跃、碰撞检测、动画播放等核心游戏机制
 */
public class Catt implements Runnable {
    public int x = 0, y = 260;//角色的初始坐标
    public int upTime;//跳跃上升的时间计数器
    public int skySpeedX, skySpeedY;//空中移动的速度
    public int speed = 5;//水平移动速度
    public int health = 100;//当前生命值
    public int coin = 0;//得分
    public Thread thread = new Thread(this);//用于控制角色行为的线程
    public Image img = new ImageIcon("img/cat/stand/26.png").getImage();//当前显示的图像
    String status = "left--right";//角色状态：左移、右移、跳跃等
    boolean isObstacle, ismove = false, direction,canRight,canLeft;//角色运动状态标志
    Image[] imageRight = new Image[3];//向右行走的动画帧
    Image[] imageLeft = new Image[3];//向左行走的动画帧
    Image[] imageLeftJump = new Image[3];//向左跳跃的动画帧
    Image[] imageRightJump = new Image[3];//向右跳跃的动画帧
    public List<Award> awards=new ArrayList<>();//奖励物品列表
    public List<Obstacle> obstacles=new ArrayList<>();//障碍物列表
    public List<Monster> monsters = new ArrayList<Monster>();//怪物列表
    public  boolean[] hpReale;//生命值显示状态数组
    private Rectangle bounds;//角色的碰撞边界矩形
    int index = 0;//动画帧索引
    int hpIndex=0;//伤害次数计数器
    public boolean restart=false;//是否需要重新开始游戏

    //初始化Ca对象，把各位运动状态放在各自数组里
    public Catt() {
        thread.start();
        //初始化动作
        this.bounds = new Rectangle(this.x, this.y, 40, 50);
        for (int i = 0; i < 3; i++) {
            imageRight[i] = new ImageIcon("img/cat/rightWalk/" + (i + 1) + ".png").getImage();
            imageLeft[i] = new ImageIcon("img/cat/leftWalk/" + (i + 1) + ".png").getImage();
            imageLeftJump[i] = new ImageIcon("img/cat/leftJump/" + (i + 1) + ".png").getImage();
            imageRightJump[i] = new ImageIcon("img/cat/rightJump/" + (i + 1) + ".png").getImage();
        }
    }



    public void sync(List<Obstacle> obstacless, List<Award> awardss, List<Monster> monsterss,boolean[] hpReales) {
        obstacles=obstacless;
        awards=awardss;
        monsters=monsterss;
        hpReale=hpReales;
    }




    //马里奥向左移动
    public void leftMove() {
        //改变速度
        skySpeedX = -5;
        //判断马里奥是否处于空中
        if (status.indexOf("jump") != -1) {
            status = "jump--left";
        } else {
            status = "move--left";
        }
        this.direction = true;
    }

    //马里奥向右移动
    public void rightMove() {
        skySpeedX = 5;

        if (status.indexOf("jump") != -1) {
            status = "jump--right";
        } else {
            status = "move--right";
        }
        this.direction = false;
    }

    //马里奥向左停止
    public void leftStop() {
        skySpeedX = 0;
        if (status.indexOf("jump") != -1) {
            status = "jump--left";
        } else {
            status = "stop--left";
        }
        this.direction = true;
    }

    //马里奥向右停止
    public void rightStop() {
        skySpeedX = 0;
        if (status.indexOf("jump") != -1) {
            status = "jump--right";
        } else {
            status = "stop--right";
        }
        this.direction = false;
    }

    //马里奥跳跃
    public void jump() {
        if (status.indexOf("jump") == -1) {
            if (status.indexOf("left") != -1) {
                status = "jump--left";
                direction = true;
            } else {
                status = "jump--right";
                direction = false;
            }
            skySpeedY = -15;
            upTime = 10;
        }

    }

    //马里奥下落
    public void fall() {
        if (status.indexOf("left") != -1) {
            status = "jump--left";
            direction = true;
        } else {
            status = "jump--right";
            direction = false;
        }
        skySpeedY = 10;
    }

    /**
     * 判断角色是否站在障碍物上方
     */
    private boolean isOnOb(Rectangle obstacleBounds) {
            // 检查角色底部是否刚好接触障碍物顶部，并且水平位置在障碍物范围内
            if (this.y + bounds.height == obstacleBounds.y && this.x + bounds.width / 2 >= obstacleBounds.x && this.x + bounds.width / 2 <= obstacleBounds.x + obstacleBounds.width) {
                return true;
            }
        return false;
    }

    @Override
    public void run() {
        while (true) {
            if (index == 3) {
                index = 0;
            };
            isObstacle = false;
            canLeft = true;
            canRight = true;

            // 判断是否在障碍物的上方
            for (Obstacle obstacle : obstacles) {
                Rectangle obstacleBounds = new Rectangle(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
                if (isOnOb(obstacleBounds)) {
                    isObstacle = true;
                    break;
                }
            }

            // 进行马里奥跳跃的操作
            jumpMove();

            // 碰撞检测
            isObstacleF();

            // 判断是否出界
            isOut();

            // 图片动态
            moveStatus();

            // 击中怪
            hitEnemy();

            // 删除奖励
            touchAward();

            // 障碍物移动跟随背景
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 检测敌人与奖励物品的碰撞，如果碰撞则移除奖励并增加金币
     */
    private void touchAward() {
        for (int i = 0; i < awards.size(); i++) {
            Award award = awards.get(i);
            if ((this.x + 25 >= award.x && this.x + 25 <= award.x + 40) && (this.y + 25 >= award.y && this.y + 25 <= award.y + 40)) {
                // 当敌人与奖励物品发生碰撞时，移除奖励并增加金币
                awards.remove(i);
                coin += 2;
            }
        }
    }


    /**
     * 处理角色与怪物的碰撞检测及伤害逻辑
     * 检测角色与怪物的碰撞，处理生命值减少、角色受伤动画切换、怪物击退和金币增加等逻辑
     */
    private void hitEnemy() {
        // 遍历所有怪物进行碰撞检测
        for (int i = 0; i < monsters.size(); i++) {
            // 获取怪物坐标
            int ey=monsters.get(i).y,ex=monsters.get(i).x;
            
            // 角色正面攻击判定：从右向左攻击
            if((this.x+35>=ex && this.x+35<=ex+10)&&(this.y+25>=ey && this.y+25<=ey+30) ) {
                // 增加受伤次数，更新生命值显示
                hpIndex++;
                hpReale[hpIndex-1]=false;
                
                // 判断是否达到最大受伤次数（3次）
                if(hpIndex==3){
                    restart=true;
                    hpIndex=0;
                }

                // 受伤后向上位移，产生击退效果
                this.y-=50;
                upTime=5;
                System.out.println("health-10");
                
                // 根据角色朝向切换受伤动画图片
                if(status.indexOf("right") != -1){
                    img=new ImageIcon("img/cat/beHit/rightBeHit.png").getImage();
                }else if(status.indexOf("left") != -1){
                    img=new ImageIcon("img/cat/beHit/leftBeHit.png").getImage();
                }
            }else if((this.x+20>=ex && this.x+20<=ex+30) && (this.y+50 == ey)){
                // 角色跳跃踩踏攻击判定
                System.out.println("dead");
                // 击杀怪物，从列表中移除
                monsters.remove(i);
                // 增加金币数量
                coin++;
            }
        }
    }

    //嘎了
    public boolean dead() {
        return restart;
    }

    //判断是否顶头
    private void isHeadTouch(Obstacle obstacle) {
        if(obstacle.y+50 == this.y && (this.x+20>=obstacle.x && this.x<= obstacle.x+50)){
            upTime=0;
            isObstacleType(obstacle);
        }
    }


    private void isObstacleType(Obstacle obstacle) {
        if(obstacle.type==1){
            // 移除类型为1的障碍物
            obstacles.remove(obstacle);
        }else if(obstacle.type==3){
            for (int i = 0; i < awards.size(); i++) {
                if(awards.get(i).id.equals(obstacle)){
                    // 触发奖励项的触摸事件
                    awards.get(i).touch();
                }
                // 更新障碍物图像为brick2.png
                obstacle.image=new ImageIcon("img/Obstacle/brick2.png").getImage();
            }
        }
    }

    //接受创建的阻碍物


    public void isObstacleF() {
        for (int i = 0; i < obstacles.size(); i++) {
            Obstacle obstacle=obstacles.get(i);
            isHeadTouch(obstacle);
            if((this.y+50 == obstacle.y)  && (this.x+20>=obstacle.x && this.x+20 <=obstacle.x+50) || y>=280){
                isObstacle = true;
            }

            //碰撞物检测
            //isWalk(obstacle);
            checkOb(new Rectangle(obstacle.x, obstacle.y, obstacle.width, obstacle.height));
        }
    }

    public void checkOb(Rectangle obstacleBounds) {
        try {
            bounds.setLocation(this.x, this.y); // 更新当前角色位置
            if (bounds.intersects(obstacleBounds)) {
                // 碰撞发生，防止角色穿过障碍物
                if (this.x < obstacleBounds.x) {
                    this.x = obstacleBounds.x - bounds.width; // 向左移动到障碍物左侧
                } else {
                    this.x = obstacleBounds.x + obstacleBounds.width; // 向右移动到障碍物右侧
                }
                // 更新边界位置
                bounds.setLocation(this.x, this.y);
            }
        } catch (Exception e) {
            System.err.println("碰撞检测时发生错误");
            e.printStackTrace();
        }
    }


    //障碍物左右碰撞逻辑
    private void isWalk(Obstacle obstacle) {
        int oy=obstacle.y,ox=obstacle.x;
        if(obstacle.type==4){
            if((this.x+30>=ox && this.x+30<=ox+10 ) &&(this.y>=oy && this.y<=oy+150)){
                this.x=obstacle.x-40;
            }
            if((this.x<=ox+65 && this.x>=ox+50) && (this.y+25>=oy && this.y+25<=oy+150)){
                this.x=obstacle.x+70;
            }
        }else{
            //右边
            if((this.x+40>=ox && this.x+40<= ox+10)&& (this.y+25>=oy && this.y+25<=oy+50)){
                System.out.println("StoprRight");
                this.x=obstacle.x-40;
            }
            //左边
            if((this.x>=ox+40 && this.x<=ox+50)&& (this.y+25>=oy && this.y+25<=oy+50)){
                this.x=obstacle.x+50;
            }
        }


    }


    //判断出界
    private void isOut() {
            x += skySpeedX;
            //判断马里奥是否到了最左边
            if (x < 0) {
                x = 0;
            }

    }

    //空中跳跃
    private void jumpMove() {
        if (isObstacle && upTime == 0) {
            if (status.indexOf("left") != -1) {
                if (skySpeedX != 0) {
                    status = "move--left";
                } else {
                    status = "stop--left";
                }
            } else {
                if (skySpeedX != 0) {
                    status = "move--right";
                } else {
                    status = "stop--right";
                }
            }
        } else {
            if (upTime != 0) {//当uptime为0时,说明跳到顶头了，可以full了
                upTime--;
            } else {
                fall();
            }
            y += skySpeedY;
        }
    }


    private void moveStatus() {
        if (status.contains("move")) {
            ismove = ismove == false ? true : false;
        }
        //判断是否向左移动
        if ("move--left".equals(status)) {
            img = imageLeft[index++];
        }
        //判断是否向右移动
        if ("move--right".equals(status)) {
            img = imageRight[index++];
        }
        //判断是否向左停止
        if (status.indexOf("stop") != -1) {
            img = new ImageIcon("img/cat/stand/26.png").getImage();
        }
        //判断是否向左跳跃
        if ("jump--left".equals(status)) {
            img = imageLeftJump[index++];
        }
        //判断是否向右跳跃
        if ("jump--right".equals(status)) {
            img = imageRightJump[index++];
        }
    }
}



